<template>
	<view class="wraper">
		<view class="header-section">
			<uni-row class="demo-uni-row" :gutter="gutter" :width="nvueWidth">
				<uni-col :span="12">
					<view class="text-container"><text class=" text-xl" style="color:black">购物车</text></view>
				</uni-col>
				<uni-col :span="12" style="display: flex; justify-content: flex-end;">
					<view v-if="isManage==false" class="text-container">
						<view @click="ManageAddress" style="display: flex;">
							<text style="text-align: right;">管理</text>
						</view>
					</view>
					<view v-if="isManage==true" class="text-container">
						<view @click="QuitManage" style="display: flex;">
							<text style="text-align: right;">退出管理</text>
						</view>
					</view>
				</uni-col>
			</uni-row>
		</view>
		<view style="overflow-y: auto; flex: 1; width: 100%;" v-if="!isLoading">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" style="height: 900rpx;" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scroll">
				<uni-card v-for="(shop,index) in shopList" :key="shop.storeId">
					<view class="title">
						<checkbox-group @change="checkboxChangeShop($event, shop)">
							<checkbox style="transform:scale(0.7)" :checked="shop.checked" />
						</checkbox-group>
						<text>{{shop.storeName}}</text>
					</view>
					<!-- 购物车条目列表 -->
					<view v-if="!isLoading">
						<view v-for="(item, idx) in shopItemListMap[shop.storeId]" :key="item.itemId">
							<uni-row class="demo-uni-row" :gutter="gutter" :width="nvueWidth">
								<uni-col :span="2">
									<checkbox-group @change="checkboxChangeGood($event,item.itemId, shop, idx)">
										<checkbox style="transform:scale(0.7)" :value="String(item.itemId)"
											:checked="item.checked" />
									</checkbox-group>
								</uni-col>
								<uni-col :span="8">
									<view @click="handleclickPicture(item.productId)">
										<image :src="baseUrl+productMap[item.productId].productLogo" mode="aspectFill"
											:style="{ width: '100px', height: '100px' }"></image>
									</view>
								</uni-col>
								<uni-col :span="12">
									<view style="display: flex; flex-direction: column;">
										<text
											style="color: #333; font-size: 18px; font-weight: bold; margin-bottom: 4px;">{{ productMap[item.productId].productName }}</text>
										<text @click="changeSpec(item,shop.storeId)"
											style="color: #666; font-size: 14px; margin-bottom: 4px;">{{ item.specName }}</text>
										<view style="display: flex; align-items: center; margin-top: 8px;">
											<text>数量:</text>
											<uni-number-box v-model="item.productCnt" />
										</view>
										<text
											class="spec-value">￥{{ formatPrice(item.specValue * item.productCnt)}}</text>
									</view>
								</uni-col>
								<uni-col :span="2" v-if="isManage==true">
									<!-- 删除按钮 -->
									<uni-icons type="minus" size="30" color="red"
										@click="deleteItem(item.itemId)"></uni-icons>
								</uni-col>
							</uni-row>
						</view>
					</view>
				</uni-card>
			</scroll-view>
		</view>
		<view class="footer" v-if="!isLoading">
			<uni-row class="demo-uni-row" :gutter="gutter" :width="nvueWidth">
				<uni-col :span="8" style="text-align: left;">
					<checkbox-group @change="checkboxChangeAll">
						<checkbox style="transform:scale(0.9)" :checked="isAllChecked" /> 全选
					</checkbox-group>
				</uni-col>
				<uni-col :span="8" style="text-align: right;">
					<!-- 合计和结算按钮 -->
					<view v-if="isManage == false"><text class="spec-value">合计:{{totalPrice}}</text></view>
				</uni-col>
				<uni-col :span="8" style="text-align: right;">
					<!-- 合计和结算按钮 -->
					<view v-if="isManage == false">
						<button class="settlement-button" size="mini" @click="addItemToOrder">结算</button>
					</view>
				</uni-col>
			</uni-row>
		</view>
		<!-- 规格选择弹窗 -->
		<uni-popup ref="specSelectionPopup" type="bottom" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">规格选择</view>
				<view class="spec-buttons">
					<view v-for="(spec, index) in availableSpecifications" :key="index" class="spec-item-container">
						<button class="spec-item-popup" :class="{ 'uni-active': selectedSpecIndex === index }"
							@click="onSpecSelected(index, spec)">
							{{ spec.specName }}
							<view>￥{{ spec.specValue }}</view>
						</button>
					</view>
				</view>
				<view class="actions">
					<button class="cancel" @click="closePopup">取消</button>
					<button class="confirm" @click="onConfirm">确定</button>
				</view>
			</view>
		</uni-popup>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#ffdbdb">
			<view style="text-align: center;font-size: 18px;">确认订单</view>
			<uni-card @click="chooseAddress">
				<text class="text-xl text-bold">地址信息：</text>
				<view style="width: 250px;">
					<view class="address-info">{{addressInfo.addressLine}}</view>
					<view class="address-name">{{addressInfo.userName}}</view>
					<view class="address-detail">{{addressInfo.userPhone}}</view>
				</view>
			</uni-card>
			<uni-row class="demo-uni-row" :gutter="gutter" :width="nvueWidth">
				<view style="text-align: center; margin-top: 10px;">
					<uni-col :span="12">
						<button size="mini" @click="cancelPopup">取消</button>
					</uni-col>
					<uni-col :span="12">
						<button size="mini" @click="confirmPopup">确定</button>
					</uni-col>
				</view>
			</uni-row>
		</uni-popup>
		<!-- 地址选择弹窗 -->
		<uni-popup ref="AddressSelectionPopup" type="bottom" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">地址选择</view>
				<view class="spec-buttons">
					<view v-for="(addr, index) in addressList" :key="index" class="spec-item-container">
						<button class="spec-item-popup" :class="{ 'uni-active': selectedAddressIndex === index }"
							@click="onAddressSelected(index, addr)">
							{{ addr.addressLine }}
						</button>
					</view>
				</view>
				<view class="actions">
					<button class="cancel" @click="closeAddressPopup()">取消</button>
					<button class="confirm" @click="onAddressConfirm()">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		AddNewOrder,
		deleteItem,
		getItemList,
		updateItem
	} from "../../api/cart";
	import {
		getAddressList
	} from "@/api/system/user.js"
	import {
		getProductDetail,
		getProductSpecifications,
	} from '@/api/login.js';
	import config from '@/config'
	import {
		getShopById
	} from "../../api/shop";
	const baseUrl = config.baseUrl
	export default {
		data() {
			return {
				gutter: 0,
				nvueWidth: 730,
				isManage: false,
				userId: '',
				addressLine: '',
				shopList: [],
				shopItemListMap: {},
				productMap: {},
				itemList: [],
				baseUrl: '',
				isLoading: true,
				scrollTop: 0,
				totalPrice: 0,
				shopTotalAmount: {},
				old: {
					scrollTop: 0
				},
				isAllChecked: false, //是否全选
				isNoChecked: true,
				addresses: {
					userId: '',
				},
				cart: {
					userId: '',
					productCnt: '',
					itemStatus: '有效',
				},
				spec: {
					itemId: '',
					specName: '',
					specValue: '',
					productCnt: 1,
					itemUnit: '',
				},
				productInofo: {
					productName: '',
					productLogo: '',
					storeId: '',
				},
				orderItem: {
					itemId: '',
					itemStatus: '',
				},
				newOrderItem: { //需要去提交到订单的
					userId: '',
					itemId: '',
					totalPrice: '',
					paymentStatus: '',
					orderStatus: '',
					userAddress: '',
				},
				addressInfo: {
					userId: '',
					userName: '',
					userPhone: '',
					addressLine: '',
				},
				addressList: [],
				itemIds: [],
				orderItemList: [], //存放待提交的条目
				availableSpecifications: [], // 后端返回的规格数据
				selectedSpecIndex: -1, // 用户选择的规格索引
				selectedAddressIndex: -1, // 选择的地址索引
				selectItemId: -1,
				selectStoreId: -1,
				msgType:'',
			}
		},
		async created() {
			this.loadContent();
			try {
				const res = await this.$store.dispatch('GetInfo');
				if (res.appUser.userId) {
					this.userId = res.appUser.userId;
					this.cart.userId = res.appUser.userId;
					this.addresses.userId = res.appUser.userId;
					this.addressInfo.userId = res.appUser.userId;
					this.addressInfo.userName = res.appUser.userName;
					this.addressInfo.userPhone = res.appUser.userPhone;
				}
				this.getProductList();
				this.getDefaultAddress();
				this.getItem();
			} catch (error) {
				console.error('Failed to get user info:', error);
				// 处理错误情况，比如显示错误消息
			}
			this.baseUrl = baseUrl;
		},

		methods: {
			loadContent() {
				uni.showLoading({
					title: '加载中...',
					mask: true,
				});
				// 模拟异步请求
				setTimeout(() => {
					// 数据请求完成后隐藏加载框
					uni.hideLoading();
					this.isLoading = false;
				}, 2000);
			},
			handleclickPicture(productId){
				this.$tab.navigateTo('/pages/category/ProductDetail/ProductDetail?productId='+productId);
			},
			formatPrice(value) { //保留两位小数
				return parseFloat(parseFloat(value).toFixed(2));
			},
			ManageAddress() {
				this.isManage = true;
			},
			QuitManage() {
				this.isManage = false;
			},
			cancelPopup() {
				this.$refs.popup.close(); // 关闭弹出层
				this.orderItemList = [];
			},
			confirmPopup() {
				// ... 确定按钮的逻辑
				this.$refs.popup.close(); // 关闭弹出层
				uni.showToast({
					title: '操作成功',
					duration: 2000
				});
				this.orderItemList.forEach(item => {
					this.newOrderItem.userId = this.userId;
					this.newOrderItem.itemId = item.itemId;
					this.newOrderItem.totalPrice = this.formatPrice(item.specValue * item.productCnt);
					this.newOrderItem.paymentStatus = "已支付";
					this.newOrderItem.orderStatus = "待发货";
					this.newOrderItem.userAddress = this.addressInfo.addressLine;
					item.itemStatus = "已支付";
					AddNewOrder(this.newOrderItem).then(res => {
						console.log(res);
					})
					this.newOrderItem = {};
					// 遍历 shopItemListMap 并删除与 itemId 匹配的条目
					Object.values(this.shopItemListMap).forEach(shopItems => {
						const index = shopItems.findIndex(shopItem => shopItem.itemId === item.itemId);
						if (index !== -1) {
							shopItems.splice(index, 1);
						}
					});
				})
				this.orderItemList = [];
			},
			changeSpec(item, storeId) {
				this.fetchProductSpecifications(item);
				console.log(item);
				this.selectItemId = item.itemId;
				this.selectStoreId = storeId;
			},
			fetchProductSpecifications(item) {
				getProductSpecifications(item.productId).then(response => {
					if (response.code === 200) {
						this.availableSpecifications = response.data;
						this.$refs.specSelectionPopup.open();
					} else {
						console.error(response.message);
					}
				}).catch(error => {
					console.error(error);
				});
			},
			closePopup() {
				this.$refs.specSelectionPopup.close();
			},
			closeAddressPopup() {
				this.$refs.AddressSelectionPopup.close();
			},
			onAddressConfirm() {
				this.addressInfo.addressLine = this.addressList[this.selectedAddressIndex].addressLine;
				console.log("6666");
			},
			dialogClose(){
				this.$refs.confirmOrder.close();
			},
			// 确认选择规格后的回调
			onSpecSelected(index, spec) {
				this.selectedSpecIndex = index;
			},
			onAddressSelected(index, spec) {
				this.selectedAddressIndex = index;
			},
			onConfirm() {
				if (this.selectedSpecIndex !== -1) {
					const spec = this.availableSpecifications[this.selectedSpecIndex];
					console.log(this.selectStoreId);
					this.shopItemListMap[this.selectStoreId].forEach(item => {
						if (item.itemId === this.selectItemId) {
							item.specValue = spec.specValue;
							item.specName = spec.specName;
							item.productCnt = 1;
							this.spec.itemId = item.itemId;
							this.spec.specName = spec.specName;
							this.spec.specValue = spec.specValue;
							this.spec.itemUnit = this.formatPrice(this.spec.specValue * 1);
							updateItem(this.spec).then(res => {
								console.log(res);
							})
						}
					})
					this.$refs.specSelectionPopup.close();
				} else {
					console.error('Please select a specification.');
				}
			},
			getDefaultAddress() {
				getAddressList(this.addresses).then(res => {
					console.log(res);
					this.addressList = res;
					// 使用 filter 方法找到所有 isdefault 等于 1 的地址
					const defaultAddresses = res.filter(address => address.isDefault === 1);

					if (defaultAddresses.length > 0) {
						// 如果找到了默认地址，您可以遍历 defaultAddresses 数组
						defaultAddresses.forEach(defaultAddress => {
							this.addressInfo.addressLine = defaultAddress.addressLine;
						});
					} else {
						console.log('没有找到默认地址');
					}
				})
			},
			chooseAddress() {
				this.addressList.forEach((address) => {});
				this.$refs.AddressSelectionPopup.open();
			},
			getItem() {
				getItemList(this.cart).then(res => {
						console.log(res);
						this.itemList = res.data;
						this.shopItemListMap = {};
						Promise.all(this.itemList.map(item => {
							return this.getShopList(item.productId).then(res => {
								if (res.code === 200) {
									const storeId = res.data.storeId;
									// 如果storeId尚未在映射中，则创建一个新的商品列表
									if (!this.shopItemListMap[storeId]) {
										this.shopItemListMap[storeId] = [];
									}
									this.shopItemListMap[storeId].push(item);
									getShopById(res.data.storeId).then(res => {
										if (!this.shopList.find(shop => shop.storeId ===
												res.data.storeId)) {
											console.log(res)
											this.shopList.push(res.data);
										}
									})
									return res.data; // 直接返回商店 ID
								}
								throw new Error('Failed to get shop list'); // 抛出一个错误，以便处理
							});
						})).then(() => {
							console.log(this.shopList); // 打印 shopList 的内容
							console.log(this.shopItemListMap);
						}).catch(error => {
							console.error(error);
						});
					})
					.catch(error => {
						console.error('Failed to get item list:', error);
						// 处理错误情况，比如显示错误消息
					});
			},
			getProductList() {
				// 获取商品列表
				getItemList(this.cart).then(res => {
					// 创建一个映射，用于存储productId对应的商品信息
					this.productMap = {};
					Promise.all(res.data.map(item => {
						return this.getShopList(item.productId).then(res => {
							if (res.code === 200) {
								this.productMap[res.data.productId] = res.data;
							} else {
								throw new Error('Failed to get product details');
							}
						});
					})).then(() => {
						// 所有商品信息已获取并存储到productMap中
						console.log(this.productMap);
					}).catch(error => {
						console.error('Failed to get product details:', error);
					});
				}).catch(error => {
					console.error('Failed to get item list:', error);
				});
			},
			getShopList(productId) {
				return getProductDetail(productId);
			},
			fetchProductDetail(productId) {
				getProductDetail(productId).then(res => {
					if (res.code === 200) {
						this.productInofo.productLogo = res.data.productLogo;
						this.productInofo.productName = res.data.productName;
						this.productInofo.storeId = res.data.storeId;
					}
				}).catch(error => {
					console.error(error);
				});
			},
			deleteItem(itemId) {
				this.itemIds.push(itemId);
				deleteItem(this.itemIds).then(res => {
					console.log(res);
					// 遍历 shopItemListMap 并删除与 itemId 匹配的条目
					Object.values(this.shopItemListMap).forEach(shopItems => {
						const index = shopItems.findIndex(item => item.itemId === itemId);
						if (index !== -1) {
							shopItems.splice(index, 1);
						}
					});
				})
			},
			addItemToOrder() {
				this.$refs.popup.open('center');
				this.shopList.forEach((shop) => {
					const items = this.shopItemListMap[shop.storeId];
					console.log(items);
					if (items) {
						items.forEach((item, index) => {
							if (item.checked) {
								this.orderItemList.push(item);
							}
						});
					}
					if (this.isNoChecked == true) { //没有选中任何商品
						//提示你还没有选择宝贝
						uni.showToast({
							title: '你还没有选择宝贝',
							icon: 'none', //如果要纯文本，不要icon，将值设为'none'
							duration: 2000 //持续时间为 2秒
						})
					}
					// 重新设置shopItemListMap，因为直接修改数组不会触发响应式更新
					this.$set(this.shopItemListMap, shop.storeId, items);
				});
				console.log(this.orderItemList);
			},
			// 全选
			checkboxChangeAll(e) {
				const isChecked = e.detail.value.length > 0;
				// 联动商家、商品
				this.shopList.forEach(shop => {
					let shopTotalAmount = 0; // 初始化商店总金额
					this.$set(shop, 'checked', isChecked);
					// 遍历shopItemList
					const goods = this.shopItemListMap[shop.storeId]; // 获取商店的商品列表
					goods.forEach(good => {
						good.checked = isChecked; // 更新商品的勾选状态
						if (shop.checked) { // 只有当商店勾选时，才计算金额
							shopTotalAmount += this.formatPrice(good.specValue * good.productCnt);
						}
					});
					this.shopTotalAmount[shop.storeId] = shopTotalAmount;
				});
				this.totalPrice = this.formatPrice(Object.values(this.shopTotalAmount).reduce((sum, amount) =>
					sum + amount, 0));
				// 更新全不选状态
				this.isNoChecked = !isChecked;
			},

			// 勾选商家
			checkboxChangeShop(e, shop) {
				const isChecked = e.detail.value.length > 0;
				let shopTotalAmount = 0; // 初始化商店总金额
				this.$set(shop, 'checked', isChecked);
				// 联动商品
				const goods = this.shopItemListMap[shop.storeId];
				goods.forEach(g => {
					this.$set(g, 'checked', isChecked)
					if (shop.checked) {
						shopTotalAmount += this.formatPrice(g.specValue * g.productCnt);
					}
				});
				this.shopTotalAmount[shop.storeId] = shopTotalAmount;
				this.totalPrice = this.formatPrice(Object.values(this.shopTotalAmount).reduce((sum, amount) =>
					sum + amount, 0));
				// 联动全选
				const shops = this.shopList
				if (isChecked) {
					let shopCheckSum = 0;
					// 判断是否所有商家都勾选
					shops.forEach(s => {
						if (s.checked) {
							shopCheckSum++
						}
					})
					this.isAllChecked = shopCheckSum === shops.length;
				} else {
					this.isAllChecked = false;
				}
				// 更新全不选状态
				this.isNoChecked = this.isAllChecked ? false : !isChecked;
			},

			// 勾选商品
			checkboxChangeGood(e, id, shop, index) {
				let shopTotalAmount = 0; // 初始化商店总金额
				const good = this.shopItemListMap[shop.storeId][index]; // 单个商品
				this.$set(good, 'checked', e.detail.value.length > 0);
				// 商品状态变更，那么再考虑商家状态
				const goods = this.shopItemListMap[shop.storeId]; // 多个商品
				let goodCheckSum = 0;
				goods.forEach(g => {
					if (g.checked) {
						goodCheckSum++;
						shopTotalAmount += this.formatPrice(g.specValue * g.productCnt);
					}
				})
				this.shopTotalAmount[shop.storeId] = shopTotalAmount;
				// 之后再判断全选
				let shopCheckSum = 0;
				this.shopList.forEach(s => {
					if (s.checked) {
						shopCheckSum++;
					}
				});
				this.totalPrice = this.formatPrice(Object.values(this.shopTotalAmount).reduce((sum, amount) =>
					sum + amount, 0));
				this.isAllChecked = shopCheckSum === this.shopList.length;
				// 更新全不选状态
				this.isNoChecked = this.isAllChecked ? false : goodCheckSum === 0;
			},

			upper: function(e) {},
			lower: function(e) {},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
		}
	}
</script>

<style>
	.header-section {
		width: 100%;
		line-height: 100rpx;
		text-align: center;
		padding: 15px;
		background-color: #ffcbb2;
	}

	.demo-uni-row {
		padding-bottom: 5px;
		padding-top: 5px;
		display: block;
	}

	.text-container {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.spec-value {
		font-size: 18px;
		color: #ff5500;
		font-weight: bold;
		margin-top: 5px;
	}

	.wraper {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}

	.footer {
		background-color: aliceblue;
		color: #000000;
		bottom: 0px;
		height: 150rpx;
	}

	/* 弹窗样式 */
	.popup-content {
		background-color: #ffffff;
		padding: 15px;
		height: 600rpx;
	}

	.popup-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.spec-buttons {
		display: flex;
		flex-wrap: wrap;
	}

	.spec-item {
		display: block;
		margin-right: 10px;
		margin-bottom: 10px;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 5px;
		font-size: 14px;
		background-color: #f5f5f5;
		cursor: pointer;
	}

	.cancel {
		background-color: #999;
		color: #ffffff;
	}

	.confirm {
		background-color: #007AFF;
		color: #ffffff;
	}

	.actions {
		display: flex;
		justify-content: space-around;
		margin-top: 20px;
	}

	.actions button {
		padding: 10px 20px;
		border-radius: 5px;
		font-size: 16px;
		cursor: pointer;
	}

	.spec-item-popup.uni-active {
		background-color: #007AFF;
		color: #ffffff;
		border-color: #007AFF;
	}

	.settlement-button {
		display: inline-block;
		background-color: #ff5500;
		/* 背景色 */
		border: 1px solid #ddd;
		/* 边框 */
		border-radius: 16px;
		/* 圆角 */
		color: #ffffff;
		/* 文字颜色 */
		font-size: 16px;
		/* 文字大小 */
		text-align: center;
		/* 文字居中 */
		cursor: pointer;
		/* 鼠标指针形状 */
	}

	.popup-content {
		align-items: center;
		justify-content: center;
		padding: 15px;
		height: 300px;
		background-color: #fff;
	}

	.popup-height {
		width: 500px;
	}

	.address-name,
	.address-phone,
	.address-detail {
		/* 根据需要设置样式 */
		display: block;
	}
</style>